/**
 * Created by zhaocong on 2016/6/16.
 * Loadimg loading 图片加载
 */
define(function (require, exports, module) {

  function Loadimg() {
    this._init();
  }

  /**
   * requestAnimationFrame
   */
  (function () {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
          window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function (callback, element) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
        var id = window.setTimeout(function () {
          callback(currTime + timeToCall);
        }, timeToCall);
        lastTime = currTime + timeToCall;
        return id;
      };
    }
    if (!window.cancelAnimationFrame) {
      window.cancelAnimationFrame = function (id) {
        clearTimeout(id);
      };
    }
  }());

  /**
   * 图片延迟加载
   * @param className
   * @param callback
   */
  Loadimg.prototype.lazy = function (className, callback) {
    $(className).each(function () {
      var _this = $(this);
      var src = _this.data('src'),
          image = new Image();
      image.src = src;
      image.onload = function () {
        _this.css('background-image', 'url(' + src + ')');
        callback ? callback() : undefined;
      }
    });
  };

  /**
   * 加载图片并返回百分比
   * @param className
   * @param callback 必须有回调函数
   */
  Loadimg.prototype.loadimg = function (className, callback) {
    var deal = $(className).length,
        size = 0;
    this.lazy(className, function () {
      size++;
      callback(size / deal * 80);
    });
  };

  /**
   * 当图片加载完毕，则隐藏loading
   * @param className
   */
  Loadimg.prototype.loading = function (className) {
    var loading = $('.loading');
    var num = 0;
    var size = 0;

    this.loadimg(className, function (deal) {
      size = deal;
      animate();
    });

    function animate() {
      var _num = num++;
      if (_num <= size + 20) {
        loading.html(_num + '%');
        requestAnimationFrame(animate);
        if(_num == 100) loading.hide();
      }
    }

    animate();
  };

  /**
   * 默认加载方法
   * @private
   */
  Loadimg.prototype._init = function () {
    console.log('Loadimg is OK (づ￣3￣)づ');
  };


  module.exports = Loadimg;
});